package br.ufpb.di.ppgi.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {
	private static final DateFormat dfLongYear = new SimpleDateFormat("dd/MM/yyyy");
	private static final DateFormat dfShortYear = new SimpleDateFormat("dd/MM/yy");
	
	private static final DateUtil instance = new DateUtil();
	public static DateUtil getInstance() {
		return instance;
	}
	
	/**
	 * Converte String de datas no formato "dd/MM/yy" ou "dd/MM/yyyy" em um objeto
	 * {@link Date}.<br>
	 * <br>
	 * parametro enviado <tt>null<tt> retorna null, sem gerar exceção. 
	 * @param date a ser convertida
	 * @return o {@link Date} convertido
	 * @throws IllegalArgumentException caso o formato esteja inv�lido.
	 */
	public Date toDate(String date) {
		if (date == null)
			return null;
		try {
			int i = date.lastIndexOf("/");
			if (date.length() - (i+1) > 2)
				return dfLongYear.parse(date);
			else
				return dfShortYear.parse(date);
		} catch (ParseException e) {
			throw new IllegalArgumentException(e);
		}
	}
	
	public String toStringShort(Date date) {
		return dfShortYear.format(date);
	}
	
	public String toStringLong(Date date) {
		return dfLongYear.format(date);
	}
	
	public String toStringTime(Date date) {
		return toString(date, "hh:mm");
	}
	
	public String toStringTimeStap(Date date) {
		return toString(date, "dd/MM/yy hh:mm");
	}
	
	public String toString(Date date,String pattern) {
		final DateFormat df = new SimpleDateFormat(pattern);
		return df.format(date);
	}

	public Date noTime(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.set(Calendar.HOUR, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		c.set(Calendar.MILLISECOND, 0);
		return c.getTime();
	}
	
	public Date lastTimeOfDay(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(noTime(date));
		c.add(Calendar.MILLISECOND, -1);
		c.add(Calendar.DATE, 1);
		return c.getTime();
	}
}
